<template>
  <div class="pageOut">
    <div class="pageIn">
      <el-form :inline="true" :model="formSearch" size="small">
        <el-form-item>
          <el-date-picker
            v-model="formSearch.time"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
          >
          </el-date-picker>
        </el-form-item>

        <el-form-item>
          <el-button icon="el-icon-search" @click="search">查询</el-button>
          <el-button
            icon="el-icon-plus"
            type="primary"
            @click="handleAdd"
            v-show="permission.add"
            >发放</el-button
          >
        </el-form-item>
      </el-form>
      <el-table
        border
        ref="table"
        :height="height - 170"
        :data="tableData"
        :header-cell-style="{ background: '#FAFAFA', color: '#606266' }"
        v-loading="loading"
        element-loading-background="rgba(255, 255, 255, 0.5)"
        style="width: 100%"
      >
        <!-- <el-table-column prop="id" width="100" label="序号"></el-table-column> -->
        <el-table-column prop="petName" label="用户名"></el-table-column>
        <el-table-column
          prop="create_time"
          :show-overflow-tooltip="tooltip"
          label="发放时间"
        ></el-table-column>
        <el-table-column
          prop="usageName"
          :show-overflow-tooltip="tooltip"
          label="状态"
        ></el-table-column>

        <el-table-column
          prop="usage_time"
          width="159"
          label="使用时间"
          align="center"
        >
        </el-table-column>
        <el-table-column
          prop="goodsName"
          label="使用商品"
          :show-overflow-tooltip="tooltip"
        >
        </el-table-column>

        <el-table-column
          prop="due_date"
          label="有效时间"
          :show-overflow-tooltip="tooltip"
        ></el-table-column>
        <el-table-column
          prop="remark"
          label="备注"
          :show-overflow-tooltip="tooltip"
        ></el-table-column>

        <el-table-column fixed="right" label="操作" width="300" align="center">
          <template slot-scope="scope">
            <el-button
              v-if="scope.row.usedStatus == 1"
              type="primary"
              size="mini"
              @click="grantClick(scope.row)"
              v-show="permission.edit"
              >回收</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="pageSizes"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        ></el-pagination>
      </div>

      <el-dialog
        append-to-body
        title="发放"
        :visible.sync="aggregateVisible"
        width="30%"
        @close="aggregateVisibleClose"
      >
        <el-form :inline="true" label-width="110px" :model="grantFrom">
          <el-form-item
            label="选择用户"
            prop="userId"
            :rules="{
              required: true,
              message: '请选择有效期',
              trigger: 'blur',
            }"
          >
            <el-select
              style="width: 300px"
              v-model="grantFrom.userId"
              placeholder="请选择用户"
              filterable
            >
              <el-option
                v-for="item in memberList"
                :key="item.id"
                :label="item.petName"
                :value="item.id"
              >
                <span style="float: left">{{ item.petName }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">{{
                  item.phone
                }}</span>
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="备注">
            <el-input
              clearable
              type="textarea"
              :rows="5"
              maxlength="300"
              show-word-limit
              v-model="grantFrom.content"
              placeholder="请输入优惠券内容"
              style="width: 300px"
            ></el-input>
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button @click="aggregateVisible = false">返 回</el-button>
          <el-button
            type="primary"
            :loading="loadingFlag"
            @click="aggregateClick"
            >确 定</el-button
          >
        </span>
      </el-dialog>
      <el-dialog
        append-to-body
        title="回收"
        :visible.sync="recycleVisible"
        width="25%"
      >
        <el-form :inline="true" label-width="90px" :model="grantFrom">
          <div class="userRow">
            您要回收 用户名：{{ userRow.petName }} 电话号码：{{
              userRow.phone
            }}
            的{{ userRow.couponName }}优惠券么?
          </div>

          <el-form-item label="备注">
            <el-input
              clearable
              type="textarea"
              :rows="5"
              maxlength="300"
              show-word-limit
              v-model="grantFrom.content"
              placeholder="请输入优惠券内容"
              style="width: 300px"
            ></el-input>
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button @click="recycleVisible = false">返 回</el-button>
          <el-button type="primary" :loading="loadingFlag" @click="recycleClick"
            >确 定</el-button
          >
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {
  couponRecord,
  addDiscount,
  editDiscount,
  delDiscount,
  cuponRelease,
  MAIN,
  memberSel,
  cuponRecovery,
} from "../../utils/api";
import UploadImage from "../../components/UploadImage";

export default {
  name: "GrantData",
  props: ["height"],
  components: {
    UploadImage,
  },
  data() {
    return {
      grantFrom: {
        userId: "",
        content: "",
      },
      memberList: [],
      userRow: {
        userName: "李四",
        phone: "133342444",
        coun: "帝王",
      },
      loadingFlag: false,
      recycleVisible: false,
      tableData: [
        {
          id: 1,
          discount_name: "帝王券",
          lowest_price: "21",
          discounts_price: "20",
          max_num: "34",
          image: "",
          commodity: "",
          valid_time: "2021-4-22",
          add_time: "2021-3-13",
          commodity: "",
        },
      ],
      userList: [],
      commodityCheck: [],
      aggregateVisible: false,
      commodityTableData: [
        {
          id: 1,
          commodityImg: "帝王券",
          commodityClass: "21",
          commodityName: "20",
          commodityClass: "34",
          price: "233",
        },
      ],
      tooltip: true, //内容过长被隐藏时显示 tooltip
      loading: true, //显示加载表格
      pageSize: 10, //每页多少条
      currentPage: 1, //当前第几页
      pageSizes: [10, 20, 30, 40, 50], //每页选择条数
      total: 0, //共多少条
      errImg: 'this.src="' + require("../../../static/img/user.png") + '"',
      permission: {
        add: false,
        edit: false,
        del: false,
      }, //权限
      comPageNumber: 1,
      comPageSize: 5,
      comTotal: 1,
      formSearch: {
        discount_name: "",
        time: "",
      }, //搜索
      //编辑弹窗
      visible: false,
      confirmLoading: false,
      type: "",
      currentRow: {}, //当前行数据信息
      ruleForm: {
        discount_name: "",
        type: "",
        max_price: "",
        min_price: "",
        money: "",
        deduction_price: "",
        image: "",
        end_time: "",
        content: "",
        addTime: "",
      }, //添加和修改的表单
      comForm: {
        commodityName: "",
      },
      params: {},
      userInfo: {},
      membeId: "",
    };
  },

  mounted() {
    this.getResource();
  },
  destroyed() {
    window.sessionStorage.removeItem("DiscountList");
  },
  created() {
    this.params = JSON.parse(window.sessionStorage.getItem("DiscountList"));
    this.postRequest(memberSel, MAIN).then((res) => {
      if (res.code === 200) {
        this.memberList = res.data;
      }
    });
  },
  methods: {
    // 回收
    recycleClick() {
      this.loadingFlag = true;
      let params = {
        memberCouponId: this.userRow.id,
        memberId: this.userRow.memberId,
        userId: this.userInfo.id,
        remark: this.grantFrom.content,
      };
      this.postRequest(cuponRecovery, params, MAIN).then((res) => {
        if (res.code === 200) {
          this.$notify.success(res.msg);
          this.recycleVisible = false;
          this.getData();
        }
        this.loadingFlag = false;
      });
    },
    getResource() {
      // console.log(this.$route.name);
      this.loading = true;
      const userinfo = JSON.parse(sessionStorage.getItem("userInfo")); //解密,获取用户登录信息
      this.userInfo = userinfo;
      let arr = userinfo.menu_id.split(",");
      // console.log(arr)
      // 发放 92
      // 回收 91
      if (arr.indexOf("92") > -1) {
        this.permission.add = true;
      }
      if (arr.indexOf("91") > -1) {
        this.permission.edit = true;
      }

      this.getData();
    },
    //清除输入框负数
    clearMinus(e, type) {
      let boolean = new RegExp("^[0-9][0-9.]*$").test(e.target.value);
      if (!boolean) {
        e.target.value = "";
        if (type === "max_price") this.ruleForm.max_price = "";
        if (type === "min_price") this.ruleForm.min_price = "";
        if (type === "money") this.ruleForm.money = "";
        if (type === "deduction_price") this.ruleForm.deduction_price = "";
      }
    },
    // 回收
    grantClick(row) {
      this.recycleVisible = true;
      this.userRow = row;
    },
    getImgSrc(e) {
      this.ruleForm.image = e;
    },
    comSearch() {
      this.comPageNumber = 1;
      this.getCommodity();
    },

    aggregateClick() {
      this.loadingFlag = true;
      let params = {
        couponId: this.params.row.id,
        memberId: this.grantFrom.userId,
        userId: this.userInfo.id,
        remark: this.grantFrom.content,
      };
      this.postRequest(cuponRelease, params, MAIN).then((res) => {
        if (res.code === 200) {
          this.loadingFlag = false;

          this.$notify.success(res.msg);
          this.aggregateVisible = false;
          this.getData();
        } else {
          this.loadingFlag = false;
        }
      });
    },
    aggregateVisibleClose() {
      this.grantFrom = {
        userId: "",
        content: "",
      };
    },
    //获取初始数据
    getData() {
      this.loading = true;
      let start_time, end_time;
      if (this.formSearch.time != "" && this.formSearch.time != null) {
        start_time = this.formSearch.time[0] + " 00:00:00";
        end_time = this.formSearch.time[1] + " 23:59:59";
      }
      let params = {
        discount_name: this.formSearch.discount_name,
        start_time,
        end_time,
        pageNumber: this.currentPage,
        pageSize: this.pageSize,
        couponId: this.params.row.id,
      };

      this.postRequest(couponRecord, params, MAIN).then((res) => {
        if (res.code == 200) {
          // console.log(res);
          this.tableData = res.data.list;
          this.total = res.data.count;
          this.loading = false;
          this.$nextTick(() => {
            //避免表格表头样式错乱
            if (this.$refs.table) this.$refs.table.doLayout();
          });
        }
      });
    },
    //分页
    comHandleSizeChange(val) {
      //每页 ${val} 条
      this.comPageSize = val;
      this.getCommodity();
    },
    comHandleCurrentChange(val) {
      //当前页
      this.comPageNumber = val;
      this.getCommodity();
    },

    //分页
    handleSizeChange(val) {
      //每页 ${val} 条
      this.pageSize = val;
      this.getData();
    },
    handleCurrentChange(val) {
      //当前页
      this.currentPage = val;
      this.getData();
    },
    //查询
    search() {
      this.getData();
    },
    //新增
    handleAdd() {
      this.type = "add";
      this.currentRow = {};
      this.aggregateVisible = true;
    },
    handleSelectionChange(val) {
      this.commodityCheck = val;
    },
    //编辑
    handleEdit(row) {
      this.type = "edit";
      this.currentRow = row;
      this.visible = true;
      this.ruleForm = {
        discount_name: row.discount_name,
        type: row.type,
        max_price: row.max_price,
        min_price: row.min_price,
        money: row.money,
        deduction_price: row.deduction_price,
        image: row.image,
        content: row.content,
        end_time: row.end_time,
      };
    },

    onConfirm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.confirmLoading = true;
          // setTimeout(() => this.onCancel(formName), 1000);
          if (this.type == "add") {
            this.addDiscount();
          } else if (this.type == "edit") {
            this.editDiscount();
          }
        } else {
          return false;
        }
      });
    },

    onCancel(formName) {
      this.$refs[formName].resetFields();
      this.onReset();
    },
    //清空重置表单
    onReset() {
      this.visible = false;
      this.confirmLoading = false;
      this.ruleForm = {
        discount_name: "",
        type: "",
        max_price: "",
        min_price: "",
        money: "",
        deduction_price: "",
        image: "",
        end_time: "",
        content: "",
      };
    },
  },
};
</script>

<style scoped>
/deep/ .el-input-group__append,
.el-input-group__prepend {
  background-color: #1890ff;
  color: #fff;
  cursor: pointer;
}
/deep/ .el-input--mini .el-input__inner {
  height: 32px;
  line-height: 32px;
}
/deep/ input::-webkit-outer-spin-button,
/deep/ input::-webkit-inner-spin-button {
  -webkit-appearance: none;
}
/deep/ input[type="number"] {
  -moz-appearance: textfield;
}
.userRow {
  margin-bottom: 20px;
  width: 70%;
  text-align: center;
  margin-left: 13%;
  line-height: 27px;
  font-size: 17px;
}
</style>
